package com.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.pojo.SysUser;
import com.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class SysUserController {
    @Autowired
    SysUserService sysUserService;

    //用户表
    @RequestMapping("/")
    public Object getList(SysUser sysUser){
        QueryWrapper<SysUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().like(sysUser.getUsrName()!=null,SysUser::getUsrName,sysUser.getUsrName());
        return sysUserService.list(queryWrapper);
    }

    //两表联查
    @RequestMapping("/getUserList")
    public Object getUserList(){
        return sysUserService.getList();
    }

    //添加
    @RequestMapping("/Add")
    public Object Add(SysUser sysUser) {
        boolean result = sysUserService.save(sysUser);
        if (result) {
            return "添加成功";
        } else {
            return "添加失败";
        }
    }

    //修改
    @RequestMapping("/Updata")
    public Object Updata(SysUser sysUser){
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(SysUser::getUsrId, sysUser.getUsrId()).set(SysUser::getUsrName, sysUser.getUsrName());
        boolean result = sysUserService.update(sysUser, updateWrapper);

        // 返回更新结果
        if (result) {
            return "更新成功";
        } else {
            return "更新失败";
        }
    }

    //删除
    @RequestMapping("/delete")
    public Object delete(SysUser sysUser) {
        QueryWrapper<SysUser> queryWrapper=new QueryWrapper();
        queryWrapper.lambda().eq( SysUser::getUsrId, sysUser.getUsrId());
        boolean result = sysUserService.remove(queryWrapper);
        if (result) {
            return "删除成功";
        } else {
            return "删除失败";
        }
    }

    @RequestMapping(value = "/login")
    public String login(String usrName, String usrPassword, Model model, HttpSession session){
        SysUser user=sysUserService.login(usrName,usrPassword);
        if (user!=null){
            session.setAttribute("loginUser", user);
            return "main";
        }else {
            model.addAttribute("msg","用户名或密码错误,登录失败!");
            return "forward:/login.jsp";
        }
    }
}

